/**
 * Created by bethinner on 5/18/16.
 */
import React, { Component } from 'react';

import {bindActionCreators} from 'redux'
import { connect} from 'react-redux'
import * as actions from '../actions/actions.js'
import Link from 'react-router/lib/Link'
import browserHistory from 'react-router/lib/browserHistory'
import NavigationBar from '../components/NavigationBar'
import MessageAlert from '../components/MessageAlert'
import cookie from 'react-cookie'
import {fetchGet,fetchPost} from '../utils/httpRequest'

class ContinueToPayContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            valueCardDetail: this.props.location.state.data,
            returnObj: {},
            clickAble: true
        }

        this._alertResult = this.alertResult.bind(this);
        this._continueToPayAlertResult = this.continueToPayAlertResult.bind(this);
        this._handle = this.handle.bind(this);
    }

    componentWillMount() {
        //this.props.cleanCancelOrderForm()
        $('#loadingToast').hide();
    }

    componentWillUnmount() {
        //this.props.cleanCancelOrderForm()

    }

    cancelOrder() {

        this.props.cancelOrderFormFetch(this.state.valueCardDetail.orderform_id);
    }

    continuePay(type) {
        sessionStorage.removeItem("payFront");

        var uid=cookie.load('mobile');
        if(!uid||uid=="undefined"){
            alert('登录失效');
            browserHistory.replace({
                pathname: '/login'
            });
            return ;
        }


        if(this.state.returnObj&&this.state.returnObj==0) {//存在取到数据未完成跳转是再发请求的情况
            return ;
        }

            if (this.state.clickAble) {

                //设置按钮不可点击
                this.state.clickAble = false;

                var uid = cookie.load("mobile");
                var orderform_code = this.state.valueCardDetail.orderform_code;

                let para = {uid: uid, orderform_id: orderform_code,wx_pay:type};
                $('#loadingToast').show();

                fetchPost('continuePay', para)
                    .then(response => response.json())
                    .then(json => {

                        $('#loadingToast').hide();
                        this.state.returnObj = json;
                        //设置按钮可点击
                        this.state.clickAble = true;
                        if (this.state.returnObj.code == 0) {
                            //获取订单信息成功
                            if (type ==0){
                                //市民卡支付
                                var form1 = document.getElementById("myform");
                                $("#reqseq").val(json.data.reqseq);
                                $("#signLicense").val(json.data.signLicense);
                                $("#apptype").val(json.data.apptype);
                                $("#smkUserId").val(json.data.smkUserId);
                                $("#FrontUrl").val(json.data.FrontUrl);
                                $("#txntype").val(json.data.txntype);
                                if(window.sessionStorage.getItem("openid")){
                                    $("#openid").val(window.sessionStorage.getItem("openid"));
                                }else{
                                    $("#openid").val("");
                                }
                                form1.submit();
                            }else {
                                window.location.href = this.state.returnObj.data;
                            }

                        }
                        this.setState({returnObj: json});
                    })

        }

    }

    goBackMyCoupons() {
        browserHistory.goBack();
    }

    handle() {
        var that = this;
        return function () {
            that.setState({returnObj: {code: -1}});
            that.props.cleanCancelOrderForm()
        }
    }
    selectPayType(){

        if (window.sessionStorage.getItem('noWx')==1){//app
            this.continuePay(0);
            return ;
        }

        var mask = $('#mask');
        var weuiActionsheet = $('#weui_actionsheet');
        weuiActionsheet.addClass('weui_actionsheet_toggle');
        mask.show()
            .focus()//加focus是为了触发一次页面的重排(reflow or layout thrashing),使mask的transition动画得以正常触发
            .addClass('weui_fade_toggle').one('click', function () {
            hideActionSheet(weuiActionsheet, mask);
        });
        $('#actionsheet_cancel').one('click', function () {
            hideActionSheet(weuiActionsheet, mask);
        });
        mask.unbind('transitionend').unbind('webkitTransitionEnd');

        function hideActionSheet(weuiActionsheet, mask) {
            weuiActionsheet.removeClass('weui_actionsheet_toggle');
            mask.removeClass('weui_fade_toggle');
            mask.on('transitionend', function () {
                mask.hide();
            }).on('webkitTransitionEnd', function () {
                mask.hide();
            })
        }
    }
    alertResult() {
        if (this.props.cancelOrderResultCode.code == 0) {
            setTimeout(this.goBackMyCoupons, 2000);
            return (<MessageAlert message="取消订单成功" type="success"/>)
        } else if (this.props.cancelOrderResultCode.code == 1) {
            return (<MessageAlert message="取消订单失败" type="error" handle={this._handle}/>)
        } else {
            return ""
        }

    }


    continueToPayAlertResult() {
        if (null != this.state.returnObj && null != this.state.returnObj.code && this.state.returnObj.code == 1) {
            return (<MessageAlert message={this.state.returnObj.msg} type="error" handle={this._handle}/>)
        } else {
            return "";
        }

    }


    render() {

        let messageAlert = this._alertResult();
        let payMessageAlert = this._continueToPayAlertResult();
        return (
            <div style={{height:"100%",
                backgroundColor:"white"}}>
                <NavigationBar Title="提交订单" LeftBar="true"/>

                    {messageAlert}
                    {payMessageAlert}
                    <form id="myform" name="myform" action="http://pay.96225.com/b2c_wap/c.action" method="post">
                        <input type="hidden" value="" name="reqseq" id="reqseq"/>
                        <input type="hidden" value="" name="signLicense" id="signLicense"/>
                        <input type="hidden" value="" name="apptype" id="apptype"/>
                        <input type="hidden" value="" name="smkUserId" id="smkUserId"/>
                        <input type="hidden" value="" name="FrontUrl" id="FrontUrl"/>
                        <input type="hidden" value="" name="txntype" id="txntype"/>
                        <input type="hidden" value="" name="openid"  id="openid"/>
                    </form>
                        <div style={{width:"100%",marginTop:"23px"}}></div>
                        <div style={parentDivStyle}>
                            <div style={bigLeftChildDivStyle}>
                                {this.state.valueCardDetail.business_name}
                            </div>
                            <div style={rightChildDivStyle}>
                                {this.state.valueCardDetail.card_name}
                            </div>
                        </div>

                        <img src="/public/img/line_icon.png"
                             style={{width:"100%"}}/>
                        <div style={parentDivStyle}>
                            <div style={leftChildDivStyle}>
                                订单总价
                            </div>
                            <div style={rightColorChildDivStyle}>
                                ¥ {this.state.valueCardDetail.money}元
                            </div>
                        </div>
                        <div style={buttonStyle} onClick={this.selectPayType.bind(this)}>
                            去支付
                        </div>
                        <div style={{
                        position: "relative",
                        marginLeft: "23px",
                        marginRight: "23px",
                        textAlign: "center"
                        }}>

                            <div style={smallRightColorChildDivStyle}>
                                <span style={smallSpanStyle} onClick={this.cancelOrder.bind(this)}>取消订单</span>
                            </div>
                        </div>

                <div id="actionSheet_wrap">
                    <div className="weui_mask_transition" id="mask"></div>
                    <div className="weui_actionsheet" id="weui_actionsheet">
                        <div className="weui_actionsheet_menu">
                            <div className="weui_actionsheet_cell" onClick={this.continuePay.bind(this,1)}>微信支付</div>
                            <div className="weui_actionsheet_cell" onClick={this.continuePay.bind(this,0)}>市民卡支付</div>
                        </div>
                        <div className="weui_actionsheet_action">
                            <div className="weui_actionsheet_cell" id="actionsheet_cancel">取消</div>
                        </div>
                    </div>
                </div>
            </div>

        )
    }
}
let buttonStyle = {
    backgroundColor: "#6BAC72",
    borderColor: "#6BAC72",
    color: "white",
    margin: "30px 23px 30px 22px",
    borderRadius: "5px",
    fontSize: "24px",
    textAlign: "center",
    height: "45px",
    lineHeight: "45px"
};
let parentDivStyle = {
    position: "relative",
    marginLeft: "23px",
    marginRight: "23px",
    minHeight: "50px",
    lineHeight:"22px"
};
let bigLeftChildDivStyle = {
    float:"left",
    fontSize: "20px",
    width:"60%",
    textAlign:"left"
};
let leftChildDivStyle = {
    position: "absolute",
    left: "0px",
    bottom: "0px",
    fontSize: "20px",
    marginTop: "23px"
};

let rightChildDivStyle = {
    float:"left",
    width:"40%",
    textAlign:"right",
    fontSize: "20px"
};
let rightColorChildDivStyle = {
    position: "absolute",
    right: "0px",
    bottom: "0px",
    fontSize: "20px",
    color: "#F89108",
    marginTop: "23px"
};
let smallRightColorChildDivStyle = {
    position: "absolute",
    right: "0px",
    bottom: "0px",
    fontSize: "12px",
    color: "#4A4A4A",
    height: "21px",
    lineHeight: "21px",
    textAlign: "center"
};
let smallSpanStyle = {
    fontSize: "16px",
    height: "21px",
    lineHeight: "21px",
    textAlign: "center",
    marginLeft: "10px"
}

function mapStateToProps(state) {
    return {
        cancelOrderResultCode: state.get('cancelOrderResultCode').toJS(),
    }


}
function mapDispatchToProps(dispatch) {

    return bindActionCreators(actions, dispatch);
}
ContinueToPayContainer.defaultProps = {}

ContinueToPayContainer.propTypes = {}


module.exports = connect(mapStateToProps, mapDispatchToProps)(ContinueToPayContainer);
